<?php
class Page{
	public $listRows   = 20;
	public function __construct($data) {
		if($data['listRows']) $this->listRows = $data['listRows'];
	}
    private $config  = array(
        'theme'   => 'Total:{total} {page}/{allpage} <a href="{first}">首页</a> <a href="{prev}">上一页</a> {list} <a href="{next}">下一页</a> <a href="{last}">尾页</a>',
		'list'    => '<a href="{url}">{p}</a>&nbsp;',
		'selected'=> '<font color="red">{p}</font>&nbsp;', 
    );
	private function get_url($page){
		$url = $_SERVER['REQUEST_URI'].(strpos($_SERVER['REQUEST_URI'],'?')?'':"?");
		$parse = parse_url($url);
		$p = empty($_GET['p'])?1:$_GET['p'];
		$p = $p-1;
		if(isset($parse['query'])) {
			parse_str($parse['query'],$params);
			unset($params['p']);
			unset($params['onepage']);
			$url   =  $parse['path'].'?'.http_build_query($params);
		}
		return $url;
    }
	public function show($db,$sql) {
		$page = empty($_GET['p'])?1:intval($_GET['p']);
		if($page<1) $page=1;
		$start = ($page-1)*$this->listRows;
		preg_match('/SELECT \* FROM\s+/',$sql,$mat);
		$csql = str_replace($mat[0],'SELECT count(*) as num FROM ',preg_replace('/order by.*/i','',$sql));
		$count = $db->getAll($csql);
		$count = $count[0]['num'];	
		$pager = '';
		$url = $this->get_url($page);
		$pagestr = '';
		if($count>0){
			$allpage = ceil($count/$this->listRows);
			$previous = '';
			$nexpage = '';
			$firstpage = $url.'&p=1';
			$lastpage = $url.'&p='.$allpage.'';

			if($page!=1){
				$previous = $url.'&p='.($page-1);
			}
			if($page!=$allpage){
				$nexpage = $url.'&p='.($page+1);
			}
			$pstr = '';
			$i=1;
			while($i<=$allpage){
				if($i == $page){
					$pstr .= str_replace(array('{p}'),array($i),$this->config['selected']);
				}else{		
					if(($page>$i-5) && ($page<$i+5)) $pstr .= str_replace(array('{url}','{p}'),array($url.'&p='.$i,$i),$this->config['list']);
				}
				$i++;
			}
			$pagestr = str_replace(array('{total}','{page}','{allpage}','{first}','{prev}','{list}','{next}','{last}'),array($count,$page,$allpage,$firstpage,$previous,$pstr,$nexpage,$lastpage),$this->config['theme']);
		}
		return array('pagestr'=>$pagestr, 'start'=>$start, 'perpage'=>$this->listRows);
		/*$jump = '<script type="text/javascript">function setonepage(){location.href=\''.$url.'\'+\'&onepage=\'+document.getElementById("onepage").value;}</script>';
		$pager = '<div>Num/Page: <input type="text" size="1" value="'.$onepage.'" name="curonepage" id="curonepage"> Total '.$count.' <a href="'.$firstpage.'">First</a> '.$previous.$pstr.$nexpage.'<a href="'.$lastpage.'">Last</a> <input name="onepage" id="onepage" type="text" size="1"> <input type="button" value="GO" onclick="setonepage()"/></div>'.$jump;*/
	}
}
?>